<template>
  <div>
    <el-row class="nav">
      <i class="el-icon-arrow-left"
         @click="goBack"></i>
      <span class="font-weight">工单详情</span>
    </el-row>
    <el-divider></el-divider>
    <!-- 按钮操作 -->
    <el-row style='margin:10px 0'>
      <el-button @click="orderOpinion"
                 type="button"
                 v-if="btnStates.EWS_add_opinion_012 && tag != 2"
                 class="el-button el-button--primary el-button--medium h30Btn  fr">追加日志</el-button>
      <el-button type="button"
                 v-if="btnStates.EWS_reminder_015 && (tag != 2 && tag != 1)"
                 @click="orderUrge"
                 class="el-button el-button--primary el-button--medium h30Btn">催单</el-button>
    </el-row>
    <el-row>
      <avue-form ref="ruleForm"
                 v-model="ruleForm"
                 :disabled="newTagInfo"
                 :option="option">
      </avue-form>
    </el-row>
    <!-- 初始节点 -->
    <el-row>
      <el-collapse v-model="activeNameStart">
        <!-- 初始节点 -->
        <el-collapse-item name="0"
                          v-if="startNodeDto.nodeName">
          <template slot="title">
            <el-col :span="8"
                    class="title">{{ startNodeDto.nodeName }}</el-col>
            <el-col :span="16"
                    style="text-align:right;">
              <span class="spans">处理人: {{ startNodeDto.handlerName }}</span>
              <span class="spans">提交时间: {{ startNodeDto.submitTime }}</span>
            </el-col>
          </template>
          <div :class="tag == 0 ? 'historyNode node' : 'node'">
            <node-form :jsonData="startNodeDto.nodeContent"
                       :formvalues="startNodeDto.nodeContent.modelValue"
                       :disabled="tag == 0 ? 'true' : 'false'"
                       @sendmsg="getMsgs"
                       ref="startForm"></node-form>
          </div>
        </el-collapse-item>
        <!-- 历史节点 -->
        <el-collapse-item v-for="(item, index) in workOrderNodeDtoList"
                          :key="item.submitTime"
                          :name="index">
          <template slot="title">
            <el-col :span="8"
                    class="title">{{ item.nodeName }}</el-col>
            <el-col :span="16"
                    style="text-align:right;">
              <span class="spans">处理人: {{ item.handlerName }}</span>
              <span class="spans">提交时间: {{ item.submitTime }}</span>
            </el-col>
          </template>
          <div v-if="item.nodeContent.config"
               :class="tag == 0 ? 'historyNode node' : 'node'">
            <node-form :jsonData="item.nodeContent"
                       :formvalues="item.nodeContent.modelValue"
                       :disabled="tag == 0 ? 'true' : 'false'"
                       @sendmsg="getMsg"></node-form>
          </div>
          <!-- 展示投管回来的信息 -->
          <div v-else
               class="node tsBusinessInfo">
            <ul>
              <li v-for="(itemInfo, index) in item.nodeContent.list"
                  :key="index">
                <el-row :gutter="20">
                  <el-col :span="8">处理人：{{ itemInfo.Performer }}</el-col>
                  <el-col :span="10">处理时间：{{ itemInfo.ActionTime }}</el-col>
                  <el-col :span="6">处理环节：{{ itemInfo.StepName }}</el-col>
                </el-row>
                <p class="problemDesc">处理意见：{{ itemInfo.Action }}</p>
              </li>
            </ul>
          </div>
        </el-collapse-item>
        <!-- 当前节点 -->
        <el-collapse-item name="now"
                          v-if="!(tag == 2||tag == 0) && nodeName">
          <template slot="title">
            <el-col :span="8"
                    class="title">{{ nodeName }}</el-col>
          </template>

          <div class="node"
               style="padding-bottom:30px;">
            <node-form v-if="jsonDatas"
                       :jsonData="jsonDatas"
                       :formvalues='currentFormValues'
                       @sendmsg="getMsg"
                       ref="mychild"></node-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-row>
    <el-row>
      <el-menu class="el-menu-demo"
               mode="horizontal"
               v-if="btnStates.EWS_all_log_017"
               @select="handleSelect">
        <el-menu-item index>
          <el-badge class="item_log"> 操作记录 </el-badge>
        </el-menu-item>
        <el-menu-item index="1">
          <el-badge :value="value1"
                    class="item_log"> 追加日志 </el-badge>
        </el-menu-item>
        <el-menu-item index="2">
          <el-badge :value="value2"
                    class="item_log"> 催单 </el-badge>
        </el-menu-item>
      </el-menu>
      <el-timeline class="relevanceList logUl"
                   v-if="btnStates.EWS_all_log_017">
        <el-timeline-item v-for="item in logList"
                          :key="item.id"
                          :timestamp="item.timestamp"
                          size="large">
          <el-row :gutter="20">
            <el-col :span="8">{{ item.createUserRoleNameStr
                }}{{
                  item.logCreaterName ? ":" + item.logCreaterName : ""
                }}</el-col>
            <el-col :span="10">{{ timestampToTime(item.logCreateTime) }}</el-col>
            <el-col :span="6">{{ item.logType }}</el-col>
          </el-row>
          <p class="problemDesc">{{ item.content }}</p>
        </el-timeline-item>
      </el-timeline>
    </el-row>
    <!-- 催单 -->
    <reminder v-if="reminderShow"
              @changeShow="orderUrgeHide"></reminder>
    <!-- 追加意见 -->
    <opinon v-if="opinionShow"
            @changeShow="opinionHide"></opinon>
  </div>
</template>
<script>
import reminder from "@/views/orderDataList/orderDialog/reminder.vue";
import { SystemField } from "@/common/generalField.js"
import { newOption } from "@/common/commonOption.js";
import common from "@/common/common.js";
import nodeForm from "@/components/common/nodeForm";
import opinon from "@/views/orderDataList/orderDialog/addOpinion";
import { getTemplateFromOfStartNode } from '@/api/workOrderTypeNode'
import {
  getWorkOrderTypeByUserId,
  getProcessMessage,
  getLoglist,
} from "@/api/workOrderController";
export default {
  props: {
    workOrderId: {
      type: String
    },
    workbenchInfo: {
      ttype: Object
    }
  },
  data () {
    return {
      userId: window.Utils.cookie.readCookie('userId'),
      formKeySign: '0',
      btnStates: window.CONFIG.btnState,
      reminderShow: false,
      opinionShow: false,
      logList: [], // 日志列表
      value1: 0,
      value2: 0,
      sizeValue: "",
      activeNameStart: ['0'],
      // activeNameStart: this.startNodeDto.nodeId?"0":'now', // 默认展开初始节点的内容
      type: [],
      classifyList: [],
      tag: "",
      startNodeDto: {
        nodeContent: {
          list: [],
          config: {
            labelWidth: 100,
            labelPosition: "top",
            size: "small"
          }
        }
      },
      getStartJsonData: {},
      jsonData: {},
      forms: {
        nodeVal: "",
        nodes: [],
        userType: "",
        userTypes: [],
        userValue: [],
        userOptions: []
      },
      ruleForm: {
        customField: {}
      },
      rulesForms: {
        nodeVal: [
          { required: true, message: "请选择节点", trigger: ["blur", "change"] }
        ],
        userType: [
          { required: true, message: "请选择类型", trigger: ["blur", "change"] }
        ],
        userValue: [
          { required: true, message: "请选择用户", trigger: ["blur", "change"] }
        ]
      },
      nodeId: "",
      nodeName: "",
      sequenceFlows: [],
      getJsonData: {},
      workOrderNodeDtoList: [],
      taskId: "",
      jsonDatas: "", // 接受form表单传过来的新值
    };
  },
  components: {
    nodeForm,
    reminder,
    opinon,
  },
  computed: {
    // activeNameStart () {
    //   return this.startNodeDto.nodeId ? "0" : 'now'
    // },

    classifyShow () {
      return this.ruleForm.workOrderTypeId && this.formKeySign === '1'
    },
    option () {
      let valueArray = {
        sizeValue: this.sizeValue,
        type: this.type,
        classifyList: this.classifyList
      };
      let formInfo = this.ruleForm.customField;
      let formFun = {
        changeRegion: '',
        changeProblem: this.changeProblem,
        classifyShow: this.classifyShow
      }
      let newOptionInfo = newOption(valueArray, formInfo, formFun)

      // 服务单类型禁用掉
      for (var i = 0; i < newOptionInfo.column.length; i++) {
        if (newOptionInfo.column[i].prop == 'workOrderTypeId') {
          newOptionInfo.column[i].disabled = true
        }
        if (newOptionInfo.column[i].prop == 'classifyData') {
          newOptionInfo.column[i].disabled = true
        }
      }
      return newOptionInfo
    }
  },
  watch: {
    jsonData (n, o) {
      this.jsonDatas = n;
    },
    reminderShow (n, o) {
      this.reminderShow = n
    },
    activeNameStart (newVal, oldVal) {
      this.activeNameStart = newVal
    }
  },
  mounted () {
    this.getWorkOrderTypeByUserIdFun()
    if (this.$store.state.orderDetailsId && this.$store.state.userId) {
      this.getProcessMessage();
    }
    this.handleSelect("");
  },
  created () {
    // this.getWorkOrderTypeByUserIdFun()
  },
  methods: {
    // 催单
    orderUrge () {
      this.reminderShow = true
    },
    // 催单弹框关闭
    orderUrgeHide (e) {
      this.reminderShow = e.value;
      if (e.name == 'submit') {
        this.handleSelect();
      }
    },
    // 追加意见弹窗关闭
    opinionHide (e) {
      if (e.name == 'submit') {
        this.handleSelect();
      }
      this.opinionShow = e.value;
    },
    // 追加意见
    orderOpinion () {
      this.opinionShow = true;
    },
    // 时间戳转换
    timestampToTime (timestamp) {
      return common.timestampToTime(timestamp);
    },
    // 查询日志列表
    handleSelect (val) {
      if (!this.$store.state.orderDetailsId) {
        return;
      }
      let params = {
        logType: val,
        workOrderId: this.$store.state.orderDetailsId || this.workOrderId,
        // 暂时处理
        currentPage: 1,
        pageSize: 1000
      };
      // 记录日志的条数
      getLoglist(params).then(res => {
        let data = res.data;
        if (data.retCode === 200) {
          if (!val) {
            this.value1 = 0;
            this.value2 = 0;
            data.data.forEach(item => {
              if (item.logType === "追加日志") {
                this.value1++;
              } else if (item.logType === "催单") {
                this.value2++;
              }
            });
          }
          this.logList = data.data;
        }
      });
    },

    goBack () {
      this.$emit('sendShowDetails', false)
    },
    setDisabledFun (dataList) {
      let _this = this
      dataList.list.forEach(x => {
        if (x.type !== 'imgupload') {
          x.options.disabled = true;
          setTimeout(() => {
            let proUploadList = document.querySelectorAll('.startNode .el-upload--picture-card')
            for (var k = 0; k < proUploadList.length; k++) {
              proUploadList[k].style.display = 'none'
            }
          }, 100);
        }
        if (x.columns) {
          x.columns.forEach(y => {
            _this.setDisabledFun(y)
          })
        }
      })
    },
    // 获取工单状态
    getProcessMessage () {
      let params = {
        id: this.$store.state.orderDetailsId || this.workOrderId,
        userId: this.$store.state.userId || this.userId
      };
      let _this = this;
      getProcessMessage(params).then(res => {
        let data = res.data;
        if (data.retCode === 200) {
          _this.ruleForm = data.data;
          _this.formKeySign = _this.ruleForm.formKeySign
          if (_this.formKeySign === '1') {
            _this.getTemplateFromOfStartNodeFun()
          }
          Object.assign(_this.ruleForm, _this.ruleForm.customField);
          // 0为表单不可编辑状态  1为可编辑状态
          _this.tag = data.data.contrOptionTag;
          _this.currentNodeDto = data.data.currentNodeDto; // 当前节点内容
          _this.nodeId = data.data.currentNodeDto.nodeId;
          _this.nodeName = data.data.currentNodeDto.nodeName;
          _this.jsonData = data.data.currentNodeDto.formTemplate;
          _this.sequenceFlows = data.data.currentNodeDto.sequenceFlows;
          _this.startNodeDto = data.data.startNodeDto;
          if (_this.startNodeDto.nodeName) {
            _this.setDisabledFun(_this.startNodeDto.nodeContent)
            _this.activeNameStart.push('now')
          }
          _this.currentFormValues = Object.assign(SystemField({}), this.jsonData.modelValue)
          // if (!data.data.tag) {
          _this.currentNodeDto.formTemplate.list.forEach(item => {
            item.options.disabled = true;
          });
          // }
          data.data.processedWorkOrderNodeDtoList.forEach((val, index) => {
            // 苏农默认全部展开
            if (window.CONFIG.itemType === '3') {
              _this.activeNameStart.push(index)
            }
            if (val.nodeContent.config) {
              _this.setDisabledFun(val.nodeContent)
            }
          });
          _this.workOrderNodeDtoList = data.data.processedWorkOrderNodeDtoList;

          _this.taskId = data.data.currentNodeDto.taskId;
          // 问题分类数据转换
          let arr = []
          if (_this.ruleForm.classifyValue) {
            if (_this.ruleForm.classifyValue.indexOf(',') < 0) {
              arr.push(Number(_this.ruleForm.classifyValue))
            } else {
              arr = _this.ruleForm.classifyValue.split(',')
              for (var i = 0; i < arr.length; i++) {
                arr[i] = Number(arr[i])
              }
            }
          } else {
            arr = []
          }
          this.ruleForm.classifyData = arr
        }
      });
    },
    // 获取问题分类
    getTemplateFromOfStartNodeFun () {
      let id = this.ruleForm.workOrderTypeId
      getTemplateFromOfStartNode(id).then(res => {
        if (res.data.retCode === 200) {
          this.classifyList = res.data.data
        }
      })
    },
    getMsg (data) {
      this.getJsonData = data;
    },
    // 初始节点获取表单数据
    getMsgs (data) {
      this.getStartJsonData = data;
    },
    getWorkOrderTypeByUserIdFun () {
      let id = 'all'
      getWorkOrderTypeByUserId(id).then(res => {
        let data = res.data;
        if (data.retCode === 200) {
          this.type = data.data
        }
      });
    },
  }
};
</script>
<style scoped>
.node {
  padding: 10px 20px;
  background: #f8f9fd;
}

.historyNode select {
  pointer-events: none;
}

.title {
  font-size: 13px;
  font-weight: bold;
}

.paging-foot {
  padding: 10px 0;
}

.el-divider--horizontal {
  margin: 20px 0;
}

.el-icon-arrow-left {
  font-size: 13px;
  color: #b60028;
  font-weight: 700;
  padding: 0 5px;
  cursor: pointer;
}

>>> .el-form-item__label {
  white-space: nowrap;
}

>>> .historyNode .el-upload .el-button--primary {
  background-color: gray;
}

>>> .is-active {
  color: #231815;
}

.tsBusinessInfo ul li:not(:last-child) {
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}
.h30Btn {
  float: right;
  margin-right: 10px;
}
.logUl {
  margin-top: 20px;
}
>>> .el-badge__content.is-fixed {
  top: 14px;
}
>>> .avue-form__menu {
  display: none;
}
</style>
